import { Request, Response } from 'express'
import { PrismaClient } from '@prisma/client'
import bcrypt from 'bcryptjs'
import jwt from 'jsonwebtoken'
import { logger } from '../services/logger'

const prisma = new PrismaClient()

// 登录
export const login = async (req: Request, res: Response) => {
    try {
        const { email, password } = req.body

        logger.info('Login attempt:', { email })

        // 验证请求数据
        if (!email || !password) {
            return res.status(400).json({ error: '请提供邮箱和密码' })
        }

        // 查找用户
        const user = await prisma.user.findFirst({
            where: { email }
        })

        if (!user) {
            logger.warn(`User not found: ${email}`)
            return res.status(401).json({ error: '用户不存在' })
        }

        // 验证密码
        const isValidPassword = await bcrypt.compare(password, user.password)
        if (!isValidPassword) {
            logger.warn(`Invalid password for user: ${email}`)
            return res.status(401).json({ error: '密码错误' })
        }

        // 生成 token
        const token = jwt.sign(
            {
                id: user.id,
                email: user.email,
                role: user.role
            },
            process.env.JWT_SECRET || 'your-secret-key',
            { expiresIn: process.env.JWT_EXPIRES_IN || '7d' }
        )

        logger.info('Login successful:', { email, userId: user.id })

        // 返回用户信息和token
        res.json({
            token,
            user: {
                id: user.id,
                email: user.email,
                username: user.username,
                role: user.role,
                avatar: user.avatar
            }
        })
    } catch (error) {
        logger.error('Login failed:', error)
        res.status(500).json({ error: '登录失败，请稍后重试' })
    }
}

// 注册
export const register = async (req: Request, res: Response) => {
    try {
        const { email, password, username } = req.body

        // 验证请求数据
        if (!email || !password || !username) {
            return res.status(400).json({ error: '请提供完整的注册信息' })
        }

        // 检查邮箱是否已存在
        const existingUser = await prisma.user.findUnique({
            where: { email }
        })

        if (existingUser) {
            return res.status(400).json({ error: '邮箱已被注册' })
        }

        // 加密密码
        const hashedPassword = await bcrypt.hash(password, 10)

        // 创建用户
        const user = await prisma.user.create({
            data: {
                email,
                password: hashedPassword,
                username,
                role: 'user'
            }
        })

        // 生成 token
        const token = jwt.sign(
            {
                id: user.id,
                email: user.email,
                role: user.role
            },
            process.env.JWT_SECRET || 'your-secret-key',
            { expiresIn: process.env.JWT_EXPIRES_IN || '7d' }
        )

        res.status(201).json({
            token,
            user: {
                id: user.id,
                email: user.email,
                username: user.username,
                role: user.role
            }
        })
    } catch (error) {
        logger.error('Registration failed:', error)
        res.status(500).json({ error: '注册失败，请稍后重试' })
    }
} 